package com.dayuanit.dy15.atm.interceptor;

import com.alibaba.fastjson.JSON;
import com.dayuanit.dy15.atm.dto.ResponseDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * controller方法执行之前调用
     * 返回true 则放行
     * 返回false 则不通过，请求不再向下传递，直接响应到终端了
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println(">>>>>>>>>>>>>preHandle");
        HttpSession session = request.getSession(false);
        //只要没登录 并且访问的地址不在unProtectedUrl集合中就挡回去
        if (null == session || null == session.getAttribute("loginUser")) {
            //不在集合中的地址就是受保护的
            System.out.println("未登录");

            //当用户没有登录，返回信息要分情况；
            //1。当前请求是异步的，也就ajax请求，则响应一个json串；
            //2.当前请求是非异步的，则重定向到登录页面

            String ajaxHeader = request.getHeader("X-Requested-With");
            if (StringUtils.isNotBlank(ajaxHeader)) {
                try {
                    response.setContentType("application/json; charset=utf-8");
                    ServletOutputStream outputStream = response.getOutputStream();

                    outputStream.write(JSON.toJSONString(ResponseDTO.unLogin("请登录")).getBytes("utf-8"));
                    outputStream.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            //重定向，原理：后台响应302状态码，终端看到是302,则在响应头获取location的值，
            //location的值就是重定向的地址，终端获取到地址后，二话不说就再次发送这个请求。
            response.sendRedirect("/");
            return false;
        }

        //如果登录 则放行 请求继续向下传递
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println(">>>>>>>>>>>>>postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println(">>>>>>>>>>>>>afterCompletion");
    }
}
